package com.bungarus.busi;

import com.bungarus.codec.protobuf.MessageProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.util.StringUtils;

/**
 *
 * Created by tang on 2018/11/11.
 */
public class ServerAuthHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        MessageProtobuf.Message message = (MessageProtobuf.Message)msg;
        MessageProtobuf.Header header = message.getHeader();
        MessageProtobuf.Credential credential = message.getHeader().getCredential();

        if(StringUtils.isEmpty(header.getSessionId())
                && StringUtils.isEmpty(header.getToken())
                && StringUtils.isEmpty(credential.getUsername())
                && StringUtils.isEmpty(credential.getPwd())){

            channelHandlerContext.fireExceptionCaught(new AuthenticationInputException());
        }
        else {
            new Authentication(channelHandlerContext).doBusiness(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        super.exceptionCaught(channelHandlerContext, throwable);
    }
}
